package com.ssh.demo.base.dao.impl;

import java.io.Serializable;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.ssh.demo.base.dao.BaseDao;
import com.ssh.demo.base.util.ReflectUtil;

public class BaseDaoImpl<T, PK extends Serializable> implements BaseDao<T, PK> {

	private SessionFactory sessionFactory;
	// Class<?>:防止报黄线,意思是传入任意类型都行,无所谓,也可以使用Object
	private Class<?> entityClass;

	public BaseDaoImpl() {
		// new出一个子类对象，父类中的this是子类中的this
		entityClass = ReflectUtil.getGenericParameterType(this.getClass());
		System.out.println("entity===>" + entityClass);
	}

	public void saveOrUpdate(T t) {
		getSession().saveOrUpdate(t);
	}

	public void del(PK pk) {
		getSession().delete(findById(pk));
	}

	public void del(T t) {
		getSession().delete(t);
	}

	@SuppressWarnings("unchecked")
	public T findById(PK pk) {
		return (T) getSession().get(entityClass, pk);
	}

	@SuppressWarnings("unchecked")
	public List<T> findAll() {
		Criteria criteria = getSession().createCriteria(entityClass);
		return criteria.list();
	}

	@SuppressWarnings("unchecked")
	public List<T> findByPage(int start, int count) {
		Criteria criteria = getSession().createCriteria(entityClass);
		criteria.setFirstResult(start);
		criteria.setMaxResults(count);
		return criteria.list();
	}

	// get
	public Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	// set
	@Resource
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

}